<template>
    <div i="upload">
        <a-upload
            :action="uploadApi"
            :disabled="disabled"
            list-type="picture-card"
            :file-list="defaultList"
            :data="uploadData"
            :headers="$header()"
            :remove='handleRemove'
            @preview="uploadPreview"
            @change="uploadChange"
        >
        <div v-if="defaultList.length < limit">
            <a-icon type="plus" />
            <div class="ant-upload-text">
                上传
            </div>
        </div>
        </a-upload>
        <a-modal :visible="previewVisible" title="预览" :footer="null" @cancel="handleCancel">
            <img style="width: 100%" :src="previewImage" />
        </a-modal>
    </div>
</template>
<script>
export default {
    name: 'upload',
    props: {
        disabled: {
            type: Boolean,
            default: false
        },
        accept: {
            type: String,
            default: 'image/*'
        },
        limit: {
            type: Number,
            default: 1
        },
        defaultList: {
            type: Array,
            default: () => []
        },
        type: {
            type: Number,
            default: 3
        }
    },
    data () {
        return {
            uploadApi: '',
            uploadData: {},
            imageList: this.defaultList,
            previewImage: '',
            previewVisible: false
        }
    },
    watch: {
        defaultList (newVal) {
            this.imageList = newVal;
        }
    },
    mounted () {
        this.init();
    },
    methods: {
        init () {
            this.uploadApi = this.$util.uploadURL()
            this.uploadData = {
                type: this.type
            }
        },
        // 改变图片
        uploadChange ({ file, fileList, event }) {
            if (file.response && file.response.code === 0) {
                fileList = fileList.map(file => {
                    if (file.response) {
                        file.url = file.response.data.imgUrl
                    }
                    return file
                })
            } else if (file.response) {
                this.$message.error(file.response.msg)
                fileList.pop()
            }
            this.$emit('change', fileList)
        },
        uploadPreview (file) {
            console.log('查看图片', file)
            this.previewImage = this.$util.getPicUrl(file)
            this.previewVisible = true
        },
        handleCancel () {
            this.previewVisible = false
        },
        handleRemove (file) {
            this.$emit('remove', file)
            return false
        }
    }
}
</script>
<style lang="scss">

</style>
